package com.qcby.mycommunity_003.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qcby.mycommunity_003.annotation.LogAnnotation;
import com.qcby.mycommunity_003.configuration.ApiConfiguration;
import com.qcby.mycommunity_003.entity.Community;
import com.qcby.mycommunity_003.entity.InOutRecord;
import com.qcby.mycommunity_003.entity.Person;
import com.qcby.mycommunity_003.form.InOutFaceForm;
import com.qcby.mycommunity_003.mapper.InOutRecordMapper;
import com.qcby.mycommunity_003.service.CommunityService;
import com.qcby.mycommunity_003.service.InOutRecordService;
import com.qcby.mycommunity_003.service.PersonService;
import com.qcby.mycommunity_003.util.Base64Util;
import com.qcby.mycommunity_003.util.FaceApi;
import com.qcby.mycommunity_003.util.Result;
import com.qcby.mycommunity_003.util.RootResp;
import com.qcby.mycommunity_003.vo.InOutListVo;
import com.qcby.mycommunity_003.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-03-25
 */
@RestController
@RequestMapping("/sys/inOut")
public class InOutRecordController {
    @Autowired
    private InOutRecordService inOutRecordService;
    @Autowired
    private CommunityService communityService;
    @Autowired
    private PersonService personService;
    @Autowired
    private InOutRecordMapper inOutRecordMapper;
    @Autowired
    private ApiConfiguration apiConfiguration;
    @Value("${upload.face}")
    private String face;
    @Value("${upload.urlPrefix}")
    private String urlPrefix;
    @GetMapping("/chart")
    public Result getchat(){
    Map charts = inOutRecordService.charts();
    return Result.ok().put("data",charts);
   }

    /**
     * 列表查询
     * @param listVo
     * @return
     */
   @GetMapping("/list")
   public Result InOutlist(InOutListVo listVo){
   PageVo pageVo=inOutRecordService.getlist(listVo);
   HashMap<String,Object> map=new HashMap<>();
   map.put("pageList",pageVo);
   return Result.ok().put("data",map);
   }

    /**
     * 小区人脸识别，下拉选择小区
     * @return
     */
   @GetMapping("/communityList")
   public Result communityList(){
       List<Community> list = communityService.list();
       return Result.ok().put("data",list);
   }

    /**
     * 图像识别
     * @param inOutFaceForm
     * @return
     */
    @LogAnnotation("进出人脸识别")
    @PostMapping("/add")
    public Result add(@RequestBody InOutFaceForm inOutFaceForm){
        //1判断是不是在人员库存在)
//        （1）调用腾讯AI接口(
        FaceApi faceApi = new FaceApi();
        RootResp resp = faceApi.searchPersonsReturnsByGroup(apiConfiguration, inOutFaceForm.getFileBase64());
        String msg = "";
//        封装人员信息的json对象
        JSONObject personInfo = null;
//        （2）根据状态码，如果是0就是在人员库
        if(resp.getRet() == 0) {
            JSONObject object = JSONObject.parseObject(resp.getData().toString());
            JSONArray resultsReturnsByGroup = object.getJSONArray("ResultsReturnsByGroup");
            JSONObject returnsByGroupJSONObject = resultsReturnsByGroup.getJSONObject(0);
            JSONArray groupCandidates = returnsByGroupJSONObject.getJSONArray("GroupCandidates");
            JSONObject groupCandidatesJSONObject = groupCandidates.getJSONObject(0);
            JSONArray candidates = groupCandidatesJSONObject.getJSONArray("Candidates");
//            （3）拿到全部人员库对象，匹配数据库人员信息
            String personId ="";
            String faceId = "";
            String personName = "";
            String faceUrl = "";
            long pid = 0;
            Person p = null, p1 = null;
            for(int i = 0;i < candidates.size();i++) {
               personInfo= candidates.getJSONObject(i);
                personId = personInfo.getString("PersonId");
                faceId = personInfo.getString("FaceId");
                personName = personInfo.getString("PersonName");
                personId = personId.substring(4);
                pid = Integer.parseInt(personId);
                p = personService.getById(pid);
                if(p == null)
                    continue;
                else
                    p1 = p;
                faceUrl = p.getFaceUrl();
                if(faceUrl == null || faceUrl.equals("")){
                    continue;
                }
                faceUrl = faceUrl.substring(faceUrl.lastIndexOf("/")+1,faceUrl.lastIndexOf("."));
                if(faceId.equals(faceUrl)) {
                    break;
                }
            }
//          (4)
            if(p==null) {
                return Result.ok().put("data","人员信息不存在");
            }
            if(inOutFaceForm.getCommunityId() != p.getCommunityId()) {
                return Result.ok().put("data","对不起，你不是本小区居民，请与系统管理员联系。");
            }
//        (5)创建出入记录对象，封装
            InOutRecord inoutrecord = new InOutRecord();
            inoutrecord.setCommunityId(p.getCommunityId());
            inoutrecord.setPersonId(p.getPersonId());
            try {
                //保存图片
                String newFileName = UUID.randomUUID()+"." + inOutFaceForm.getExtName();
                String fileName = face + newFileName;
                Base64Util.decoderBase64File(inOutFaceForm.getFileBase64(),fileName);
                String basePath = urlPrefix + "community/upload/face/" + newFileName;
                //查找系统中是否有该人员的出入场信息
                InOutRecord inoutrecord1 = this.inOutRecordMapper.getInOutRecord(inoutrecord);
//        （6）根据出去等于null来查，如果查不到就新建一个对象，查到了就是出去小区
                //进入小区
                if(inoutrecord1 == null) {
                    inoutrecord.setInPic(basePath);
                    this.inOutRecordMapper.insert(inoutrecord);
                    return Result.ok().put("status", "success").put("data", "【"+p.getUserName() + "】进入小区");
                    //离开小区
                } else {
                    inoutrecord1.setOutPic(basePath);
                    inoutrecord1.setOutTime(new Date());
                    this.inOutRecordMapper.updateById(inoutrecord1);
                    return Result.ok().put("status", "success").put("data", "【"+p.getUserName() + "】离开小区");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            msg = "人脸识别失败,错误码=" + resp.getRet() + "," + resp.getMsg();
        }
        return Result.ok().put("data",msg);
//<==========================以上是腾讯api接口================================================================>
//        //模拟人脸识别
//        String fileBase64 = inOutFaceForm.getFileBase64();
//        String faceBase = fileBase64.substring(0, 60);
//        //如果不是头像
//        if(faceBase.equals("iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAAAXNSR0IArs4c")) {
//            return Result.ok().put("status", "fail").put("data", "人脸识别失败");
//        }
//        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("face_base", faceBase);
//        Person person = this.personService.getOne(queryWrapper);
//        if(person == null) {
//            return Result.ok().put("status", "fail").put("data", "人员信息不存在");
//        }
//        if(inOutFaceForm.getCommunityId() != person.getCommunityId()) {
//            return Result.ok().put("status", "fail").put("data", "对不起，你不是本小区居民，请与系统管理员联系");
//        }
//        InOutRecord inOutRecord = new InOutRecord();
//        inOutRecord.setCommunityId(person.getCommunityId());
//        inOutRecord.setPersonId(person.getPersonId());
//        try {
//            //保存图片
//            String newFileName = UUID.randomUUID()+"." + inOutFaceForm.getExtName();
//            String fileName = face + newFileName;
//            Base64Util.decoderBase64File(fileBase64,fileName);
//            String basePath = urlPrefix + "community/upload/face/" + newFileName;
//            //查找系统中是否有该人员的出入场信息
//            InOutRecord inOutRecord1 = inOutRecordMapper.getInOutRecord(inOutRecord);
//            //进入小区
//            if(inOutRecord1 == null) {
//                inOutRecord.setInPic(basePath);
//                this.inOutRecordMapper.insert(inOutRecord);
//                return Result.ok().put("status", "success").put("data", "【"+person.getUserName() + "】进入小区");
//                //离开小区
//            } else {
//                inOutRecord1.setOutPic(basePath);
//                this.inOutRecordMapper.updateById(inOutRecord1);
//                return Result.ok().put("status", "success").put("data", "【"+person.getUserName() + "】离开小区");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
    }
}

